package com.hzhjhh.view.cashierView;

import java.awt.Font;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Objects;
import java.util.Optional;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.apache.commons.lang3.StringUtils;

import com.hzhjhh.entity.UserInfo;
import com.hzhjhh.mapper.UserInfoMapper;
import com.hzhjhh.util.DBUtils;

/**
 * 组件初始化-收银页面-会员卡号
 * @author 12083
 *
 */
public class VipCardIdInit {

	private static final UserInfoMapper userInfoMapper = DBUtils.getSqlSession(true).getMapper(UserInfoMapper.class);
	
	/**
	 * 初始化会员卡号-标签
	 */
	public static JLabel initLb() {
		JLabel vipCardId = new JLabel();
		vipCardId.setText("会员卡号");
		vipCardId.setBounds(30, 488, 48, 15);
		return vipCardId;
	}
	/**
	 * 初始化会员卡号-输入框
	 * 
	 * @param discount 折扣输入框
	 */
	public static JTextField initTxf(JTextField discount) {
		JTextField vipCardId = new JTextField();
		vipCardId.setFont(new Font("宋体", Font.PLAIN, 20));
		vipCardId.setBounds(91, 489, 152, 21);
		// 添加失焦事件
		vipCardId.addFocusListener(new FocusAdapter() {

			@Override
			public void focusLost(FocusEvent e) {
				queryUserInfo(vipCardId, discount);
			}
			
		});
		// 添加按键事件
		vipCardId.addKeyListener(new KeyAdapter() {

			@Override
			public void keyPressed(KeyEvent e) {
				// 只有回车时处理
				if (e.getKeyCode() != KeyEvent.VK_ENTER) {
					return;
				}
				queryUserInfo(vipCardId, discount);
			}
			
		});
		return vipCardId;
	}
	
	/**
	 * 查询会员信息
	 * 
	 * @param vipCardId 会员卡号
	 */
	private static void queryUserInfo(JTextField vipCardId, JTextField discount) {
		String vipCardNum = vipCardId.getText();
		if (StringUtils.isBlank(vipCardNum)) {
			return;
		}
		// 查询会员卡信息
		// private static final String select5 = "select * from UserManage where CardId=? ";
		UserInfo userInfo = userInfoMapper.selectByCardId(vipCardNum);
		if (Objects.isNull(userInfo)) {
			JOptionPane.showMessageDialog(vipCardId, "无此卡号", "错误", JOptionPane.ERROR_MESSAGE);
			return;
		}
		discount.setText(
				Optional.ofNullable(userInfo.getDiscount())
					.map(item -> item.toString())
					.orElse(null)
		);
		vipCardId.setEditable(false);
	}
}
